/*
 * Copyright (c) 2012, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.bmi.gwt.mi.client.impl;

import java.util.ArrayList;
import java.util.HashMap;

import org.bmi.gwt.mi.shared.MiObject;
import org.bmi.gwt.mi.shared.MiProxy;
import org.bmi.gwt.mi.shared.communication.ptypes.Param;
import org.bmi.gwt.mi.shared.exceptions.NotAvailableConstructorException;
import org.bmi.gwt.mi.shared.util.ObjectWrapper;
import org.bmi.gwt.mi.shared.util.WrapperFactory;

public abstract class WrapperFactoryClient implements WrapperFactory
{
	protected HashMap<String, InnerWrapperFactory> wFactorysMap;
	protected ArrayList<InnerWrapperFactory> wFactoryList;

	public interface InnerWrapperFactory
	{
		ObjectWrapperClient create();

		/**
		 * Returns a wrapper with a prepared instance, generated by a
		 * constructor defined by a signature and a buffer of arguments.
		 * 
		 * @param signature Object constructor signature.
		 * @param objectMap The map of registered objects. Required in case an
		 *        {@link MiObject} should be returned.
		 * @param args Array of {@link Param} wrapping constructor arguments.
		 * @return The requested wrapper.
		 */
		ObjectWrapperClient create(String signature, HashMap<String, ObjectWrapper> objectMap, Param<?>[] args)
				throws Exception;

		/**
		 * Returns a wrapper with a prepared instance, generated by a
		 * constructor defined by a signature and a buffer of arguments. This
		 * method should be used in transactional environments.
		 * 
		 * @param signature Object constructor signature.
		 * @param returnValuesMap Map which for each returned variable ID
		 *        provides its real value.
		 * @param objectMap The map of registered objects. Required in case an
		 *        {@link MiObject} should be returned.
		 * @param args Array of {@link Param} wrapping constructor arguments.
		 * @return
		 * @throws Exception
		 */
		ObjectWrapper create(String signature, HashMap<String, Object> returnValuesMap,
				HashMap<String, ObjectWrapper> objectMap, Param<?>[] args) throws Exception;

		/**
		 * Returns true when the provided object can be wrapped by this object.
		 * Typically the provided object should be an instance of some type
		 * extending {@link MiObject} targeted ion some {@link MiProxy} class.
		 * 
		 * @param miObject The object to be wrapped.
		 * @return
		 */
		boolean accept(MiObject miObject);
	}

	protected WrapperFactoryClient()
	{
		this.wFactorysMap = new HashMap<String, InnerWrapperFactory>();
		this.wFactoryList = new ArrayList<InnerWrapperFactory>(50);
	}

	@Override
	public <T extends MiObject> ObjectWrapperClient createWrapper(T miObject)
	{
		/*
		 * In case the target MiObject is an implementable class (not abstract)
		 * then the wrapper should be localized directly from the map
		 */
		InnerWrapperFactory w = this.wFactorysMap.get(miObject.getClass().getName());

		if (w == null)
		{
			/*
			 * In such case it has been found some implementation or subclass of
			 * the target MiObject.
			 */
			for (InnerWrapperFactory d : this.wFactoryList)
				if (d.accept(miObject))
				{
					ObjectWrapperClient wrapper = d.create();
					wrapper.setInstance(miObject);

					return wrapper;
				}

			/* Shouldn't be possible */
			return null;
		}

		ObjectWrapperClient wrapper = w.create();
		wrapper.setInstance(miObject);

		return wrapper;
	}

	@Override
	public ObjectWrapperClient createWrapper(Class<? extends MiObject> objectClass, String signature,
			HashMap<String, ObjectWrapper> objectMap, Param<?>[] args) throws Exception
	{
		InnerWrapperFactory wrapper = this.wFactorysMap.get(objectClass.getName());

		if (wrapper == null)
			throw new NotAvailableConstructorException("The constructor of " + objectClass.getName()
					+ " is not available since it's not a MiObject directly targeted by a proxy.");

		return wrapper.create(signature, objectMap, args);
	}

	@Override
	public ObjectWrapperClient createWrapper(String targetClassName, String signature,
			HashMap<String, ObjectWrapper> objectMap, Param<?>[] args) throws Exception
	{
		InnerWrapperFactory wrapper = this.wFactorysMap.get(targetClassName);

		if (wrapper == null)
			throw new NotAvailableConstructorException("The constructor of " + targetClassName
					+ " is not available since it's not a MiObject directly targeted by a proxy.");

		return wrapper.create(signature, objectMap, args);
	}

	@Override
	public ObjectWrapper createWrapper(Class<? extends MiObject> objectClass, String argsSignature,
			HashMap<String, Object> returnValuesMap, HashMap<String, ObjectWrapper> objectMap,
			Param<?>[] constructorArgs) throws Exception
	{
		InnerWrapperFactory wrapper = this.wFactorysMap.get(objectClass.getName());

		if (wrapper == null)
			throw new NotAvailableConstructorException("The constructor of " + objectClass.getName()
					+ " is not available since it's not a MiObject directly targeted by a proxy.");

		return wrapper.create(argsSignature, returnValuesMap, objectMap, constructorArgs);
	}

	@Override
	public ObjectWrapper createWrapper(String targetClassName, String argsSignature,
			HashMap<String, Object> returnValuesMap, HashMap<String, ObjectWrapper> objectMap,
			Param<?>[] constructorArgs) throws Exception
	{
		InnerWrapperFactory wrapper = this.wFactorysMap.get(targetClassName);

		if (wrapper == null)
			throw new NotAvailableConstructorException("The constructor of " + targetClassName
					+ " is not available since it's not a MiObject directly targeted by a proxy.");

		return wrapper.create(argsSignature, returnValuesMap, objectMap, constructorArgs);
	}
}
